package manager;

import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;



/**
 * 
 * @desc 线程池的代理类，提交任务，执行任务，移除任务
 * @author Anson-pc
 * 
 */
public class ThreadPoolExecutorProxy {
	
	ThreadPoolExecutor mThreadPoolExecutor;
	private int corePoolSize;
	private int maximumPoolSize;
	private long keepAliveTime;
	
	
	public ThreadPoolExecutorProxy(int corePoolSize, int maximumPoolSize,
			long keepAliveTime) {
		super();
		this.corePoolSize = corePoolSize;
		this.maximumPoolSize = maximumPoolSize;
		this.keepAliveTime = keepAliveTime;
	}

	/**
	 * 提交任务
	 */
	public Future<?> submit(Runnable task) {
		initThreadPoolExecutor();
		
		return mThreadPoolExecutor.submit(task);
	}

	/**初始化线程池*/
	private void initThreadPoolExecutor() {
		/**
		 * 单例的设计模式
		 * 1.一个类只有一个实例
		 * 2.一个类里面的成员变量只有一个实例
		 */
		if (mThreadPoolExecutor == null || mThreadPoolExecutor.isShutdown() || mThreadPoolExecutor.isTerminated()) {
			synchronized (ThreadPoolExecutor.class) {
				if (mThreadPoolExecutor == null || mThreadPoolExecutor.isShutdown() || mThreadPoolExecutor.isTerminated()) {
					TimeUnit unit = TimeUnit.MILLISECONDS;
		            BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>() ;
				
		            ThreadFactory threadFactory = Executors.defaultThreadFactory();
		            RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();
					
					//创建mThreadPoolExecutor实例
					mThreadPoolExecutor = new ThreadPoolExecutor(
							corePoolSize, //核心线程池的大小
							maximumPoolSize, //线程池最大线程数
							keepAliveTime, //保持时间
							unit, //时间单位
							workQueue, //任务队列
							threadFactory, //线程工厂
							handler);//异常的捕捉器
							
				}
				}
			}
			
		
	}

	/**
	 * 执行任务
	 */
	public void execute(Runnable task) {
		initThreadPoolExecutor();
		mThreadPoolExecutor.execute(task);
	}

	/**
	 * 移除任务
	 */
	public void remove(Runnable task) {
		initThreadPoolExecutor();
		mThreadPoolExecutor.remove(task);
	}

}
